import { isArray, isObject } from '@/utils/util';
import { rulesMap } from './rules_map';
import { merge as _merge } from 'lodash';

export default {
  getFlatConfig(obj, pKey = '', resObj = {}) {
    const _resObj = resObj || {};
    if (isArray(obj)) {
      for (let i = 0; i < obj.length; i++) {
        const key = pKey ? `${pKey}.[x]` : '[x]';
        this.getFlatConfig(obj[i], key, _resObj);
      }
    } else if (isObject(obj)) {
      Object.entries(obj).map(([i]) => {
        const key = pKey ? `${pKey}.${i}` : i;
        this.getFlatConfig(obj[i], key, _resObj);
      });
    } else {
      let type = typeof obj;
      const arr = ['string', 'number', 'boolean'];
      if (arr.includes(type)) {
        type = `desc_${type}`;
      } else {
        type = 'desc_string';
      }
      _resObj[pKey] = {
        type,
        exampleValue: obj,
      };
    }
    return _resObj;
  },

  mergeRulesMap(flatConfig) {
    const _rulesMap = {};
    Object.entries(rulesMap).map(([i]) => {
      const val = JSON.parse(JSON.stringify(rulesMap[i]));
      let key = i;
      if (!/^(config\.property|config\.data|events\.)/.test(i)) {
        key = `config.property.${i}`;
      }
      _rulesMap[key] = val;
    });

    const allRules = _merge({}, flatConfig, _rulesMap);
    return allRules;
  },
};
